/*
 * @lc app=leetcode.cn id=59 lang=javascript
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    let arr=new Array(n).fill(0).map((item)=>{
        return new Array(n).fill(false)
    })
    let count=1
    dfs=function(i,j){
        if(arr[i][j]===false){
            arr[i][j]=count
            count++
            if(count-1==n*n)return
        }
        if(!arr[i][j+1]&&j+1<n&&(arr[i-1]==undefined||arr[i-1][j]!==false)){
            dfs(i,j+1)
        }else if(i+1<n&&!arr[i+1][j]){
            dfs(i+1,j)
        }else if(!arr[i][j-1]&&j-1>=0){
            dfs(i,j-1)
        }else{
            dfs(i-1,j)
        }
    }
    dfs(0,0)
    return arr
};
console.log(generateMatrix(3))
// @lc code=end

var generateMatrix = function(n) {
    let _result = Array.from({ length: n }, () => Array(n))
    let num = 1,
        rowStart = 0, // 行首边界
        rowEnd = n - 1, // 行尾边界
        columnStart = 0, // 列首边界
        columnEnd = n - 1 // 列尾边界
    while (num <= n * n) {
        // 首行
        for (let i = columnStart; i <= columnEnd; i++) {
            _result[rowStart][i] = num++
        }
        rowStart++
        // 尾列
        for (let i = rowStart; i <= rowEnd; i++) {
            _result[i][columnEnd] = num++
        }
        columnEnd--
        // 尾行
        for (let i = columnEnd; i >= columnStart; i--) {
            _result[rowEnd][i] = num++
        }
        rowEnd--
        // 首列
        for (let i = rowEnd; i >= rowStart; i--) {
            _result[i][columnStart] = num++
        }
        columnStart++
    }
    return _result
};//循环填充法